# -*- coding: utf-8 -*- #

import urllib2
import json

CLIENT_SECRET_FILE = 'client_secrets.json'
URL = 'https://accounts.google.com/o/oauth2/device/code'
URL_ENDPOINT = 'https://www.googleapis.com/oauth2/v3/token'
GMAIL_SCOPE = '&scope=email profile'


def get_oauth_user_code(url, data):
    """ Return the object data from the first call to google oauth. """
    req = urllib2.Request(url, data)
    json_data = urllib2.urlopen(req).read()
    f = open("oauth_data.json", "w")
    f.write(json_data)
    f.close()
    pyt_data = json.loads(json_data)
    return pyt_data


def poll_oauth(url, data):
    """ Return the object data from the first call to google oauth. 
    :rtype : object
    """

    req = urllib2.Request(url, data)
    try:
        json_data = urllib2.urlopen(req).read()
        f = open("poll_oauth_data.json", "w")
        f.write(json_data)
        f.close()
        pyt_data = json.loads(json_data)
        return pyt_data
    except:
        return 0


def get_client_secret(file_name):
    """ Return the data from the json file. """
    json_client_secret_data = open(file_name).read()
    py_client_secret_data = json.loads(json_client_secret_data)
    # client_secret = py_client_secret_data['installed']['client_secret']
    return py_client_secret_data

if __name__ == '__main__':

    client_secret_object = get_client_secret(CLIENT_SECRET_FILE)
    CLIENT_ID = client_secret_object['installed']['client_id']
    CLIENT_SECRET = client_secret_object['installed']['client_secret']
    print "client id = ", CLIENT_ID
    print "client secret = ", CLIENT_SECRET

    data_for_url = "client_id=" + CLIENT_ID + GMAIL_SCOPE
    print data_for_url
    user_code_object = get_oauth_user_code(URL, data_for_url)
    DEVICE_CODE = user_code_object["device_code"]
    VERIFICATION_URL = user_code_object["verification_url"]
    USER_CODE = user_code_object["user_code"]

    print "device code = ", DEVICE_CODE
    print "verification url = ", VERIFICATION_URL
    print "user code = ", USER_CODE

    data_for_url = "client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&code=" + DEVICE_CODE +\
                   "&grant_type=http://oauth.net/grant_type/device/1.0"

    print data_for_url
    person = input('go to web and type the user code')
    access_token_object = poll_oauth(URL_ENDPOINT, data_for_url)
